define(function (require, exports, module) {
	
	var CPDF_Annot = FXREADER.PDFData.CPDF_Annot;
    var CAnnotFactory = FXREADER.CAnnotFactory;
	
    FXREADER.Event.CommentAnnotToolHandler = function (annotType,annotPlugin) {
    	var _pReaderApp = null,
    		_pBaseAnnotPlugin = annotPlugin,
    		_commentAnnotType = annotType,
    		_isProcessing = false,
    		_pTextSelectTool = null,
    		_self = this;
    	
    	var DEFAULT_OPCITY = 1.0;
    	var MKA_POPUPWIDTH = 180;
    	var MKA_POPUPHEIGHT = 120;

        /**
        * @description 初始化工具时调用
        * @param {FXREADER.CReaderApp} pReaderApp App对象
        */
        this.Tool_OnInit = function (pReaderApp) {
            _pReaderApp = pReaderApp;
            if (FXREADER.TextSelect && FXREADER.TextSelect.CReader_TextSelectTool) {
                _pTextSelectTool = new FXREADER.TextSelect.CReader_TextSelectTool.CreateTextSelectTool(pReaderApp, true);
            }
        };
        
        /**
        * @description 获取工具的名称
        * @return {String} 工具的名称;
        */
        this.Tool_GetName = function () {
            return _commentAnnotType;
        };

        // UI Events
        /**
        * @description 激活工具时调用
        */
        this.Tool_OnActivate = function () {
        	if (_pReaderApp.GetMainView() != null) {
                 var pDocView = _pReaderApp.GetMainView().GetDocView();
                 var jqDocViewContainer = $("#" + pDocView.GetDocViewContainerID());
                 jqDocViewContainer.css({ 'cursor': "auto" });
            }
            var pCommentAnnotCommand = null;
            if(_commentAnnotType===FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_HIGHLIGHT)
            {
            	pCommentAnnotCommand = _pReaderApp.GetCommand("HighlightAnnotCommand");
            }
            else if(_commentAnnotType===FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_UNDERLINE)
            {
            	pCommentAnnotCommand = _pReaderApp.GetCommand("UnderlineAnnotCommand");
            }
            pCommentAnnotCommand && pCommentAnnotCommand.SetState(true);
        };
        
        
        /**
        * @description 停用工具时调用
        */
        this.Tool_OnDeactivate = function () { 
            var pCommentAnnotCommand = null;
            if(_commentAnnotType===FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_HIGHLIGHT)
            {
            	pCommentAnnotCommand = _pReaderApp.GetCommand("HighlightAnnotCommand");
            }
            else if(_commentAnnotType===FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_UNDERLINE)
            {
            	pCommentAnnotCommand = _pReaderApp.GetCommand("UnderlineAnnotCommand");
            }
            pCommentAnnotCommand && pCommentAnnotCommand.SetState(false);
        };

        // Calculate status
        /**
        * @description 判断该工具是否可用
        * @return {Boolean} 可用返回true,否则返回false;
        */
        this.Tool_IsEnabled = function () {
            var pCurrentDocument = _pReaderApp.GetMainView().GetDocView().GetPDFDoc();
            if (pCurrentDocument) {
                if (pCurrentDocument.GetDocType() != FXREADER.PDFData.DocType.XFA)
                    return true;
            }
            /*
             * if (!(pDoc->GetDocumentType() == DOCTYPE_DYNIMIC_XFA))
			return pDoc->GetPermissions(FPDFPERM_ANNOT_FORM) ; 
             * */
            return true;
        };
        
        /**
         * @description 判断该工具是否正处于文本选择状态
         * @return {Boolean} 正处于文本选择状态返回true,否则返回false;
         */
         this.Tool_IsProcessing = function () {
             return _isProcessing;
         };

         // Mouse events
         /**
         * @description 鼠标左键按下事件处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnLButtonDown = function (event) {
        	 var pDocView = _pReaderApp.GetMainView().GetDocView();
             var jqDocViewContainer = $("#" + pDocView.GetDocViewContainerID());
             if (!FXREADER.Common.ContainsNode(jqDocViewContainer.get(0), event.target, true)) {
                 return false;
             }
             
             var pPageView = null, ptOffsetCurPageView = new  FXREADER.CPDF_Point(0, 0);
             pPageView = FXREADER.TextSelect.CReader_TextSelectTool.GetPageViewInfoByMouseEvent(_pReaderApp, event, ptOffsetCurPageView, true, false);
             if(pPageView == null)
            	 return false;
             var pAnnot = pPageView.GetAnnotAtPoint(event,null);
             if(pAnnot)
             {
            	 if (pAnnot.GetType() === _commentAnnotType)
         			return false;
             }
             
             var pFocusAnnot = pPageView.GetFocusAnnot();
         	 if (pFocusAnnot)
         	 {
         		pPageView.SetFocusAnnot(null);
         	 }
         	 pPageView.GetDocView().ClearAllSelection();
             
        	 _pTextSelectTool.Select_OnLButtonDown(event);
        	 _isProcessing = true;
             return true;
         };
         
         /**
         * @description 鼠标左键弹起事件处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnLButtonUp = function (event) {
        	 	_ClearHighLightRectsSelected();
        		if (_isProcessing)
        		{		
        			_pTextSelectTool.Select_OnLButtonUp(event,function(){
        				_self.CreateAnnot();
            			_pReaderApp.GetMainView().GetDocView().SetChangeMark();
        			});
        		}
        		_pTextSelectTool.ClearSelection();
        		_isProcessing = false;
        		return true;
         };
         
         function _ClearHighLightRectsSelected(pageIndex, bNoClearData) {
             var pDocView = _pReaderApp.GetMainView().GetDocView();
             if (pageIndex && pageIndex >= 0) {
                 var pPageView = pDocView.GetPageView(pageIndex);
                 if (pPageView) {
                     var highLightSelectedDivID = pPageView.GetPageContainerID() + "_TextSelectedHighLightsSelected";
                     var jqHighlightSelectedDiv = $("#" + highLightSelectedDivID);
                     if (jqHighlightSelectedDiv.length > 0) {
                         jqHighlightSelectedDiv.empty();
                     }
                 }

              /*   if (!bNoClearData) {
                     if (pageIndex == _downInHightTextInfo.pageIndex) {
                         _downInHightTextInfo.pageIndex = -1;
                         _downInHightTextInfo.hightTextRectIndex = -1;
                     }
                 }*/
                 return;
             
             }
             var pageCount = pDocView.GetPageCount();
             for (var i = 0; i < pageCount; i++) {
                 var pPageView = pDocView.GetPageView(i);
                 if (pPageView) {
                     var highLightSelectedDivID = pPageView.GetPageContainerID() + "_TextSelectedHighLightsSelected";
                     var jqHighlightSelectedDiv = $("#" + highLightSelectedDivID);
                     if (jqHighlightSelectedDiv.length > 0) {
                         jqHighlightSelectedDiv.empty();
                     }
                 }
             }

             /*if (!bNoClearData) {
                 _downInHightTextInfo.pageIndex = -1;
                 _downInHightTextInfo.hightTextRectIndex = -1;
             }*/
         }
         
         function _GetDefaultColor(annotType)
         {
         		if (annotType === FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_UNDERLINE)
         		{
         			return "#00ff00";
         		}
         		else if (annotType === FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_HIGHLIGHT)
         		{
         			return "#ffff00";
         		}
         		else return "ffff00";
         }
         
         function _GetDefaultSubj(annotType)
         {
        		if (annotType === FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_UNDERLINE)
        			return "Underline";
        		else if (annotType == FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_HIGHLIGHT)
        			return "Highlight";
        		else if (annotType == FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_SQUIGGLY)
        			return "Squiggly";
        		else if (annotType == FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_STRIKEOUT)
        			return "Strikeout";
        		else if (annotType == FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_CARET)
        			return "Caret";
        		else if (annotType == FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_REPLACE)
        			return "Replace";
        		return "";
         }
         
         
         function _CreateAnnot(pPDFPage,rectArray)
         {
        	 if(rectArray.length < 0)
        		 return false;
        	 var timestamp = (new Date()).valueOf();
        	 var annots_json = {
        			 c : "",
        			 ca :DEFAULT_OPCITY,
        		     cd : timestamp,
        		     cl : _GetDefaultColor(_commentAnnotType),
        		     f : FXREADER.PDFData.AnnotFlag.ANNOTFLAG_PRINT,
        		     md : timestamp,
        		     n : timestamp,
        		     pop :null,
        		     subj : _GetDefaultSubj(_commentAnnotType),
        		     subty : _commentAnnotType,
        		     tit : "Administrator",
        		     ty : "Markup",
        		     Quad : [],
        		     rc: null
        	 };
        	 FXREADER.RectUtils.Normalize(rectArray[0]);
        	 var totalRect = rectArray[0];
        	 annots_json.Quad.push(totalRect.left,totalRect.top,totalRect.right,totalRect.top,totalRect.left,totalRect.bottom,totalRect.right,totalRect.bottom);
        	 for (var i = 1; i < rectArray.length; i++) {
                 var rect = rectArray[i];
                 annots_json.Quad.push(rect.left,rect.top,rect.right,rect.top,rect.left,rect.bottom,rect.right,rect.bottom);
                 FXREADER.RectUtils.Normalize(rect);
                 FXREADER.RectUtils.Union(totalRect, rect);  
             }
        	 annots_json.rc = [totalRect.left,totalRect.top,totalRect.right,totalRect.bottom];
        	 
        	 var popupRect = new FXREADER.CPDF_Rect(0, 0, 0, 0);
        	 popupRect.top = totalRect.top;
        	 popupRect.right = pPDFPage.GetPageWidth(); 
        	 popupRect.left = popupRect.right - MKA_POPUPWIDTH ; 
        	 popupRect.bottom = popupRect.top - MKA_POPUPHEIGHT ; 
        	 
        	 annots_json.pop = 
        	 {
        			 f :  FXREADER.PDFData.AnnotFlag.ANNOTFLAG_PRINT,
        			 md : timestamp,
        			 n : timestamp,
        			 op : 0,
        			 rc : [popupRect.left,popupRect.top,popupRect.right,popupRect.bottom] 
        	 };
        	 
        	 var pAnnot = CAnnotFactory.CreateAnnot(annots_json,false);
             pPDFPage.AddAnnot(pAnnot);
             var pPageView = _pReaderApp.GetMainView().GetDocView().GetPageView(pPDFPage.GetPageIndex());
             var pageAnnotsDiv = _pBaseAnnotPlugin.GetHandlerManager().GetPageAnnotsContainerID(pPageView);
             var jqPageAnnotsDiv = $("#"+pageAnnotsDiv);
             var newAnnotHtml = _pBaseAnnotPlugin.GetHandlerManager().CreateAAnnotHtmlContent(pPageView,pAnnot,pPDFPage.GetAnnotsCount()-1);
             jqPageAnnotsDiv.append(newAnnotHtml);
         }
         
         this.CreateAnnot = function()
         {
        	 var nStartPageIndex = 0 , nEndPageIndex = 0;
        	 var selectRange = _pTextSelectTool.Select_GetPageRange(nStartPageIndex , nEndPageIndex);
        	 nStartPageIndex = selectRange.start;
        	 nEndPageIndex = selectRange.end;
        		if (nEndPageIndex < 0 || nStartPageIndex < 0)
        			return false;

        		var iPageNum = Math.abs(nEndPageIndex - nStartPageIndex) + 1;
        		var iStep = nEndPageIndex - nStartPageIndex >= 0 ? 1 : -1;
        		for (var iPageIndex = nStartPageIndex, iIndex = 0; iIndex < iPageNum; iPageIndex += iStep, iIndex++)
        		{
        			var pPage = _pTextSelectTool.GetTextPage(iPageIndex);
        	        if (!pPage) return;
        	        var rect_array = [];
        	        pPage.pageSelectInfo.GetSelectPDFRect(rect_array);
        			if (rect_array.length > 0)
        			{	
        				var pPDFPage = _pReaderApp.GetMainView().GetDocView().GetPageView(iPageIndex).GetPDFPage();
        				_CreateAnnot(pPDFPage,rect_array);
        			}
        		}
        		return true;
         };
         
         
         
         /**
         * @description 鼠标左键双击事件处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnLButtonDblClk = function (event) {
        	 var pDocView = _pReaderApp.GetMainView().GetDocView();
             var jqDocViewContainer = $("#" + pDocView.GetDocViewContainerID());
             if (!FXREADER.Common.ContainsNode(jqDocViewContainer.get(0), event.target, true)) {
                 return false;
             }
             
             var pPageView = null, ptOffsetCurPageView = new FXREADER.CPDF_Point(0, 0);
             pPageView = FXREADER.TextSelect.CReader_TextSelectTool.GetPageViewInfoByMouseEvent(_pReaderApp, event, ptOffsetCurPageView, true, false);
             if(pPageView == null)
            	 return false;
             var pAnnot = pPageView.GetAnnotAtPoint(event,null);
             if(pAnnot)
             {
            	 if (pAnnot.GetType() === _commentAnnotType)
         			return false;
             }
             
             var pFocusAnnot = pPageView.GetFocusAnnot();
         	 if (pFocusAnnot)
         	 {
         		pPageView.SetFocusAnnot(null);
         	 }
         	 pPageView.GetDocView().ClearAllSelection();
             
        	 _pTextSelectTool.Select_OnLButtonDblClk(event,function(){
 				_self.CreateAnnot();
    			_pReaderApp.GetMainView().GetDocView().SetChangeMark();
			});
             return true;
         };
         /**
         * @description 主窗体的鼠标移动事件处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnMouseMove = function (event) {
        	 _pTextSelectTool.Select_OnMouseMove(event);
             return true;
         };
         /**
         * @description 鼠标右键按下事件处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnRButtonDown = function (event) {
             return false;
         };
         /**
         * @description 鼠标右键弹起事件处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnRButtonUp = function (event) {
             return false;
         };
         /**
         * @description 鼠标右键双击事件处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnRButtonDblClk = function (event) {
             return false;
         };
         /**
         * @description 鼠标滚轮滚动事件处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnMouseWheel = function (event) {
             return false;
         };
         /**
         * @description 鼠标移进事件（鼠标移动到它子元素时也会触发该事件）处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnMouseOver = function (event) {
             return false;
         };
         /**
         * @description 鼠标移出事件（鼠标移动到它子元素时也会触发该事件）处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnMouseOut = function (event) {
             return false;
         };
         /**
         * @description 鼠标进入事件（鼠标只有进入该元素区域才会触发该事件）处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */ 
         this.Tool_OnMouseEnter = function (event) {
             return false;
         };
         /**
         * @description 鼠标离开事件（鼠标只有离开该元素区域才会触发该事件）处理
         * @param {object} event 鼠标事件对象
         * @return {Boolean} 处理返回true,否则返回false;
         */
         this.Tool_OnMouseLeave = function (event) {
             return false;
         };
    };

    return FXREADER.Event.CommentAnnotToolHandler;
});